package com.lepu.app.fun.my;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemLongClickListener;

import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.MyDialog;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.lepu.app.fun.my.adapter.AdapterMyVideo;
import com.lepu.app.fun.my.bean.BeanMyArticle;
import com.lepu.app.fun.my.bean.BeanQuestionAnswer;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

/**
 * 我的 视频，和我收藏的视频 共用
 * @author wxd
 *
 */
public class MyVideoActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest, OnRefreshListener,
		OnLoadListener,Observer{

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 20;
	private static final int MSG_DATA_FAIL = 21;
	private static final int MSG_DATA_MORE_SUCCESS = 22;
	private static final int MSG_DATA_MORE_FAIL = 23;

	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterMyVideo mDataAdapter = null;
	private ArrayList<BeanMyArticle> mDataArrayList = null;
	private int mCurrentPage = 1;
	private String mRefreshTime = "";
	
	//collect
	public int mCurrentOpePosition = 0;
	private boolean mIsCollect = false;
	public BeanMyArticle mCurrentBeanMyArticle = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		mNeedDefaultUmeng = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_video_activity);

		init();
	}

    @Override
	public void onResume() {
        super.onResume();

        UmengHelper.onResume(this, UmengEvent.page_shipinjicui);
    }

    @Override
	public void onPause() {
        super.onPause();

        UmengHelper.onPause(this, UmengEvent.page_shipinjicui);
    }
	
	@Override
	public void onDestroy() {
		super.onDestroy();

		ObserverManager.getInstance().removeObserver(this);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("视频集粹");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mIsCollect = getIntent().getBooleanExtra("IsCollect", false);

		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);
		
		if(mIsCollect)
		{
			//长按，取消收藏
			mDataListView.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View view,
						int position, long id) {
					
					BeanMyArticle item = mDataArrayList.get(position);
					cancelCollect(item.TargetID, position);
					return false;//default false
				}
			});
		}else{

			ObserverManager.getInstance().addObserver(
					ObserverConst.NOTIFY_INDEX_UPDATE_VIDEO_LIST, this);
		}

		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				mGoogleRefreshLayout.setRefreshing(true);  //直接调用是没有用的
			}
		}, 100);
		requestList(false);
	}

	private void showHideNoDataLayout(boolean isShow) {
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if (noDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					noDataLayout.setVisibility(View.VISIBLE);
				}else{
					noDataLayout.setVisibility(View.GONE);
				}
			} else {
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showFirstLoadDataLayout(boolean isShow) {
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if (firstLoadDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}

				LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
			} else {
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	public void removeItem()
	{
		if(mIsCollect)
		{
			mDataArrayList.remove(mCurrentOpePosition);
			mDataAdapter.notifyDataSetChanged();
			
			if(mDataArrayList == null || mDataArrayList.size() == 0){
				showHideNoDataLayout(true);
			}
		}
	}

	public void addItem()
	{
		if(mIsCollect)
		{
			mDataArrayList.add(mCurrentOpePosition,mCurrentBeanMyArticle);
			mDataAdapter.notifyDataSetChanged();
		}
	}

	// 请求数据
	public void requestList(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}
		
		String url = Setting.getArticleListUrl();
		if(mIsCollect)
		{
			url = Setting.getUserCollectListUrl();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			if(mIsCollect)
			{
				//1：文章 2：视频 3：帖子
				params.put("TargetType", 2);
			}else{
				params.put("ACIDList", "24");//视频
				//params.put("ArticleTitle", "");
				params.put("RefreshTime", mRefreshTime);
				params.put("SortDirection", "DESC");

				String version = getPackageManager().getPackageInfo(
						getPackageName(), 0).versionName;
				params.put("ClientVersion", version);
			}

			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
		} catch (Exception e) {
		}
		map.put("ht", params);
		
		ApiClient.http_post(url, map, null, this,
				request, true, false, true);
	}
	
	//======================================================
	/**
	 * 取消收藏
	 * @param TargetID
	 * @param position
	 */
	public void cancelCollect(final String TargetID,final int position) {
		
		String message = "您确定取消收藏吗？";
		MyDialog dialog = new MyDialog(this)
				.setMessage(message)
				.setNegativeButton(R.string.app_cancel,
						R.drawable.btn_cancel_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok,
						R.drawable.btn_ok_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								mCurrentOpePosition = position;
								requestCancelCollect(TargetID);
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}
	
	/**
	 * 取消收藏 请求
	 * @param TargetID
	 */
	private void requestCancelCollect(String TargetID)
	{
		MyNetUtil.getInstance().requestCancelCollect(this, this,
				MyNetUtil.REQUEST_CANCEL_COLLECT, 2, TargetID);
	}
	//=================================================

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanMyArticle> dataList = (ArrayList<BeanMyArticle>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataArrayList = dataList;
				} else {
					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
					
//					UIHelper.showToast(MyVideoActivity.this,
//							R.string.no_data);
					showHideNoDataLayout(true);
				}

				ImageView tempImageView = new ImageView(MyVideoActivity.this);
				mDataListView.addHeaderView(tempImageView);

				mDataAdapter = new AdapterMyVideo(MyVideoActivity.this,
						mDataArrayList,mIsCollect);
				mDataListView.setAdapter(mDataAdapter);

				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
					}
				}, 100);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:
				// 更新完后调用该方法结束刷新
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
					}
				}, 100);

				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanMyArticle> dataMoreList = (ArrayList<BeanMyArticle>) msg.obj;

				if (dataMoreList != null && dataMoreList.size() > 0) {

					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MyVideoActivity.this,
							R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		requestList(true);
	}

	@Override
	public void onRefresh() {
		requestList(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			ArrayList<BeanMyArticle> dataArraylist = BeanMyArticle
					.parseListInfo((String) data);

			if(!mIsCollect)
			{
				mRefreshTime = BeanMyArticle.parseDetailInfo((String) data).RefreshTime;
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			ArrayList<BeanMyArticle> dataMoreArraylist = BeanMyArticle
					.parseListInfo((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				mDataArrayList.addAll(dataMoreArraylist);
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		}else if (object.equals(MyNetUtil.REQUEST_CANCEL_COLLECT)) {
			hideProgressDialog();
			
			removeItem();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		}else if (object.equals(MyNetUtil.REQUEST_CANCEL_COLLECT)) {
			hideProgressDialog();
		}
	}

	@Override
	public void notify(String name, Object sender, Object data) {
		if(name.equals(ObserverConst.NOTIFY_INDEX_UPDATE_VIDEO_LIST))
		{
			Integer position = (Integer) sender;
			BeanMyArticle beanMyArticle = (BeanMyArticle) data;

			if(beanMyArticle == null)
			{
				return;
			}

			mDataArrayList.get(position).FavourCount = beanMyArticle.FavourCount;
			mDataArrayList.get(position).ViewCount = beanMyArticle.ViewCount;

			mDataAdapter.notifyDataSetChanged();
		}
	}
}
